package com.douwong.student.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.douwong.student.R;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseActivity;
import com.douwong.student.model.StatusCode;
import com.douwong.student.model.UserBean;
import com.douwong.student.rxjava.EndPointInterface;
import com.douwong.student.rxjava.NetWork;
import com.douwong.student.utils.DateTools;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.CircleTransform;
import com.douwong.student.view.PersonInfoItemView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Calendar;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.douwong.student.R.id.user_head;

/**
 * @autor yichao
 * @time 2017/3/279:50
 * @des 个人信息
 */
public class PersonInfoActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "PersonInfoActivity";

    private PersonInfoItemView mItemViewName, mItemViewAccount, mItemViewClass, mItemViewSex, mItemViewBirthy, mItemViewAge, mItemViewSchool;
    private ImageView mIvBack, mIvUserHean;
    private boolean inforModify = false;
    private File mSdcardTempFile;
    private Bitmap mBmp;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_personinfo);
        mIvBack = (ImageView) findViewById(R.id.go_back_img);
        mIvUserHean = (ImageView) findViewById(user_head);
        mItemViewName = (PersonInfoItemView) findViewById(R.id.itemview_name);
        mItemViewAccount = (PersonInfoItemView) findViewById(R.id.itemview_account);
        mItemViewClass = (PersonInfoItemView) findViewById(R.id.itemview_classes);
        mItemViewSex = (PersonInfoItemView) findViewById(R.id.itemview_sex);
        mItemViewBirthy = (PersonInfoItemView) findViewById(R.id.itemview_birthty);
        mItemViewAge = (PersonInfoItemView) findViewById(R.id.itemview_age);
        mItemViewSchool = (PersonInfoItemView) findViewById(R.id.itemview_school);

    }

    @Override
    protected void initData() {
        if (BaseApplication.sUserBean != null) {
            UserBean userBean = BaseApplication.sUserBean;
            mItemViewName.setViewName(userBean.getPersonalbean().getRealName() + "");
            mItemViewAccount.setViewName(userBean.getUserbean().getEuNumber() + "");
            mItemViewSex.setViewName(userBean.getPersonalbean().getSex() == 0 ? "男" : "女");
            mItemViewBirthy.setViewName(userBean.getPersonalbean().getBirthday() == null ? "" : DateTools.getDateByString(userBean.getPersonalbean().getBirthday()));
            mItemViewSchool.setViewName(userBean.getSchoolbean().getFullName() == null ? "" : userBean.getSchoolbean().getFullName());
            if (userBean.getPersonalbean().getBirthday() != null && !userBean.getPersonalbean().getBirthday().equals("")) {
                String birthday = userBean.getPersonalbean().getBirthday();
                Calendar calendar = Calendar.getInstance();
                String year = birthday.substring(0, 4);
                mItemViewAge.setViewName(String.valueOf(calendar.get(Calendar.YEAR) - Integer.valueOf(year)));
            }
            if (userBean.getClassbean() != null) {
                mItemViewClass.setViewName(userBean.getClassbean().getName() == null ? "" : userBean.getClassbean().getName());
            }

            if (userBean.getPersonalbean().getHeadPortrait() == null || userBean.getPersonalbean().getHeadPortrait().equals("")) {
                mIvUserHean.setImageResource(BaseApplication.sUserBean.getPersonalbean().getSex() == 0 ? R.mipmap.boy_default
                        : R.mipmap.girl_default);
            } else {
                Glide.with(this)
                        .load(EndPointInterface.HEAD_PIC + BaseApplication.sUserBean.getPersonalbean().getHeadPortrait())
                        .placeholder(R.mipmap.signin)
                        .transform(new CircleTransform(this))
                        .into(mIvUserHean);
            }
        }
        mSdcardTempFile = new File(FileUtils.IMAGE_DIR, "tmpphoto" + ".jpg");

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mIvBack.setOnClickListener(this);
        mIvUserHean.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_back_img:
                setResult(MainActivity.SetPersonInfoResponeCode);
                finish();
                break;
            case user_head:
                //头像
                getPic();
                break;
        }

    }
    private AlertDialog dialog;
    private final int ALBUM_REQUEST_CODE = 500;
    private final int CAMERA_REQUEST_CODE = 600;
    private void getPic() {
        if (dialog == null) {
            dialog = new AlertDialog.Builder(this)
                    .setItems(new String[] { "拍照", "相册" }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                startActivityForResult(intent, CAMERA_REQUEST_CODE);
                            } else {

                                Intent intent = new Intent(Intent.ACTION_PICK,
                                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                                startActivityForResult(intent, ALBUM_REQUEST_CODE);
                            }
                        }
                    }).create();
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (resultCode==RESULT_OK){
           switch (requestCode) {
               case  CAMERA_REQUEST_CODE:
                    //相机
                   try {
                       mBmp = (Bitmap) data.getExtras().get("data");
                       mBmp.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(mSdcardTempFile));
                       upLoadPic(mSdcardTempFile);
                   } catch (FileNotFoundException e) {
                       e.printStackTrace();
                   }
                   break;
               case ALBUM_REQUEST_CODE:
                   //相册
                   Uri selectedImage = data.getData();
                   String[] filePathColumns = { MediaStore.Images.Media.DATA };
                   Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                   int i = 0;
                   if (c.moveToNext()) {
                       int columnIndex = c.getColumnIndex(filePathColumns[i]);
                       String filePath = c.getString(columnIndex);
                       File file = new File(filePath);
                       if (file.length() > 200 * 1024) {
                           BitmapFactory.Options options = new BitmapFactory.Options();
                           options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                           mBmp = BitmapFactory.decodeFile(filePath, options);
                       } else {
                           mBmp = BitmapFactory.decodeFile(filePath);
                       }
                       upLoadPic(file);
                   }
                   c.close();

                   break;
           }
       }
    }

    /**
     * 上传图片
     * @param sdcardTempFile
     */
    private void upLoadPic(final File sdcardTempFile) {
        unsubscribe();
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), sdcardTempFile);
        MultipartBody.Part photo = MultipartBody.Part.createFormData("myfile", sdcardTempFile.getName(), photoRequestBody);
        NetWork.getHeadEndPointInterface().uploadPic(photo,RequestBody.create(null, BaseApplication.sUserBean.getUserbean().getId()+""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StatusCode<String>>() {
                    @Override
                    public void onCompleted() {
                        logcatI("上传完成");
                    }
                    @Override
                    public void onError(Throwable e) {
                        logcatI("上传错误"+e.toString());
                        ToastUtils.makeText(PersonInfoActivity.this,"上传错误"+e.toString());
                    }
                    @Override
                    public void onNext(StatusCode<String> stringStatusCode) {

                        if (stringStatusCode.isFlag()) {
                            inforModify = true;
                            Glide.with(PersonInfoActivity.this)
                                    .load(sdcardTempFile)
                                    .placeholder(R.mipmap.signin)
                                    .transform(new CircleTransform(PersonInfoActivity.this))
                                    .into(mIvUserHean);
                        }else {
                            ToastUtils.makeText(PersonInfoActivity.this,stringStatusCode.getMsg());
                        }

                      logcatI(  stringStatusCode.toString());


                    }
                });


        /*try {
            // Toast.makeText(this, sdcardTempFile.length()/1024+"",
            // Toast.LENGTH_LONG).show();
            RequestParams params = new RequestParams();
*//*          params.addBodyParameter("userId", BaseApplication.sUserBean.getUserbean().getId()+"");
            params.addBodyParameter("myfile ", sdcardTempFile);  *//*
            params.addBodyParameter("userid", BaseApplication.sUserBean.getUserbean().getId()+"");
            params.addBodyParameter("myfile ", sdcardTempFile);
            new HttpUtils().send(HttpRequest.HttpMethod.POST, NetConfig.UPLOAD_HEAD_PIC, params, new RequestCallBack<String>(this) {

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    LogUtils.i(TAG,"上传头像失败"+arg0.toString()+arg1);
                }

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {

                    StatusCode<String> sc = JSON.parseObject(arg0.result, new TypeReference<StatusCode<String>>() {
                    });
                    if (sc != null) {
                        if (sc.isFlag()) {
                            inforModify = true;
                         //   user_head.setImageBitmap(bmp);
                        }
                       // Toast.makeText(PersonInforActivity.this, sc.getDetailMsg(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }*/

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (inforModify == true) {
                setResult(MainActivity.SetPersonInfoResponeCode);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
